package cc.idoone.spring_boot_hello.interceptors;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * HandlerInterceptor 测试
 *
 * @author hemj
 * @since 2017/10/22
 */
public class LoginInterceptor implements HandlerInterceptor {

	private static final Logger logger = LoggerFactory.getLogger(LoginInterceptor.class);

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		if (!(handler instanceof HandlerMethod)) {
			return true;
		}

		HandlerMethod handlerMethod = (HandlerMethod) handler;
		Method method = handlerMethod.getMethod();

		LoginRequired methodAnnotation = method.getAnnotation(LoginRequired.class);
		if (methodAnnotation != null) {
			// 在这里时行是否登录判断
			// ...
			String exTest = request.getParameter("ex");
			if (exTest != null) {
				throw new Exception("用户未登录");
			}
		}
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest httpServletRequest,
						   HttpServletResponse httpServletResponse, Object handler, ModelAndView modelAndView) throws Exception {
		logger.info("postHandle");
	}

	@Override
	public void afterCompletion(HttpServletRequest httpServletRequest,
								HttpServletResponse httpServletResponse, Object handler, Exception exception) throws Exception {
		logger.info("afterCompletion");
		if (exception != null) {
			logger.error("logger", exception);
		}
	}
}
